package com.example.deliveryapplication.sql

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.example.deliveryapplication.entity.*

@Database(version = 2, entities = [Client::class,BearingModel::class,BearingType::class,Plan::class,PlanItem::class,CU::class],exportSchema = false)
abstract class AppDatabase : RoomDatabase() {

    abstract fun clientDao(): ClientDao
    abstract fun bearingModelDao():BearingModelDao
    abstract fun bearingTypeDao():BearTypeDao
    abstract fun planDao():PlanDao
    abstract fun planItemDao():PlanItemDao
    abstract fun cuDao():CUDao
    companion object {
        val MIGRATION_1_2=object : Migration(1,2){
            override fun migrate(database: SupportSQLiteDatabase) {
                //2->3
//                database.execSQL("alter table CurrentChartEntity add column read int not null default 0")
//                database.execSQL("alter table ChartListEntity add column online int not null default 0")
                //3->4
                database.execSQL("CREATE TABLE IF NOT EXISTS `CU` (`cuId` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL)")
                database.execSQL("alter table PlanItem add column cu TEXT NOT NULL DEFAULT ''")
            }
        }

        private var instance: AppDatabase? = null

        @Synchronized
        fun getDatabase(context: Context):AppDatabase{
            instance?.let {
                return it
            }
            return  Room.databaseBuilder(context.applicationContext,AppDatabase::class.java,"app_database")
                .addMigrations(MIGRATION_1_2)
                //.fallbackToDestructiveMigration()
                .build().apply {
                    instance=this
                }
        }
    }
}